<template>
  <div>
    <el-form class="query-table-form" @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          auto-top
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="项目名称查询"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.res_person"
          placeholder="负责人查询"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          v-model="params['extended_loan_type.eq']"
          :options="enumRiskType"
          placeholder="申请类型"
          clearable
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-plus" @click="handleEdit()">登记</el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :stripe="false" :columns="tableColumns" :data="tableData">
      <template v-slot:status="scope">
        <div :class="`text-${scope.row.statusColor}`">
          <div>{{ scope.row.statusLabel }}</div>
          <small>{{ scope.row.finishDate }}</small>
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <renewal-edit-dialog
      :visible.sync="editVisible"
      :renewal-data="editRow"
      :view-mode="viewMode"
      @success="getData(params.index)"
    ></renewal-edit-dialog>

    <post-view :visible.sync="viewVisible" :related-id="viewId" tab-name="renewal">
      <template v-slot:header>
        <el-tab-pane :label="`${viewRenewalData.riskType || ''}信息`" name="renewal">
          <renewal-base
            :visible="viewVisible"
            :renewal-data="viewRenewalData"
            :view-mode="3"
          ></renewal-base>
        </el-tab-pane>
      </template>
    </post-view>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  enumRiskType,
  enumPostponeStatus,
  enumPostponeStatusColor,
  enumRenewalStatus,
  enumRenewalStatusColor,
} from '@/credit/views/city/risk/riskMixins'
import { pureDot } from '@/common/filters/pure'
import { MANAGE_JOBS } from '@/credit/plugins/constant'

import SelectAddress from '@/components/select/SelectAddress'
import RenewalEditDialog from '@/credit/views/city/risk/RenewalEditDialog'
import PostView from '@/credit/views/city/risk/PostView'
import RenewalBase from '@/credit/views/city/risk/RenewalBase'

export default {
  components: {
    SelectAddress,
    RenewalEditDialog,
    PostView,
    RenewalBase,
  },
  props: {},
  data() {
    return {
      enumRiskType,
      loading: false,
      params: {
        index: 1,
        size: 15,
        address_code: '',
        customer_name: '',
        res_person: '',
        'extended_loan_type.eq': '',
      },
      order: {
        create_time: 'desc',
      },
      tableName: 'credit_extended_loan',
      totalCount: 0,
      tableData: [],
      tableColumns: [
        {
          attrs: { label: '主体名称', prop: 'customer_name', align: 'center' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '地址', prop: 'address', align: 'center' } },
        { attrs: { label: '负责人', prop: 'corp_name', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'mobile_no', align: 'center' } },
        { attrs: { label: '申请时间', prop: 'createTime', align: 'center' } },
        { attrs: { label: '申请类型', prop: 'riskType', align: 'center' } },
        { attrs: { label: '申请状态', align: 'center' }, slot: 'status' },
        {
          attrs: { label: '操作', align: 'center' },
          operations: [
            {
              content: '审批',
              icon: 'fa fa-gavel',
              event: this.handleApproval,
              // 审批委员审批
              ifRender: r => this.isApprovalRep && r.approval_status === 0,
            },
            {
              content: '修改',
              icon: 'fa fa-edit',
              event: this.handleEdit,
              ifRender: r => this.userId === r.res_a && r.approval_status === 0,
            },
            {
              content: '完成',
              icon: 'fa fa-check-square-o',
              event: this.handleFinish,
              ifRender: r => this.userId === r.res_a && r.approval_status === 1,
            },
            {
              content: '查看',
              icon: 'fa fa-search',
              event: this.handleView,
            },
            // { content: '删除', icon: 'fa fa-trash', event: this.handleDelete }
          ],
        },
      ],

      // edit
      editVisible: false,
      editRow: {},
      viewMode: 0, // 0-修改 1-审批 2-完成 3-查看

      // 查看
      viewId: '',
      viewVisible: false,
      viewRenewalData: {},
    }
  },
  computed: {
    ...mapGetters(['userId', 'clientId', 'user', 'job']),
    isManager() {
      return MANAGE_JOBS.includes(this.job) || this.isApprovalRep
    },
    isApprovalRep() {
      return this.job === 'org_c_manage'
    },
  },
  watch: {},
  created() {
    this.params['service_id.eq'] = this.clientId
    if (!this.isManager) {
      this.params['orWhere.res_a.eq'] = this.userId
      this.params['orWhere.res_b.eq'] = this.userId
    }
    this.getData()
  },
  mounted() {},
  methods: {
    fetchData() {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, this.params, this.order)
      )
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res] = await this.fetchData()
      this.loading = false

      const data = (res && res.data) || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.dataAdapter)
    },
    dataAdapter(item) {
      item.left_funds = pureDot(item.left_funds || '')
      item.approval_status = +item.approval_status
      item.extended_loan_type = +item.extended_loan_type
      item.createTime = this.$utils.dateFormat(item.create_time, 'yyyy-MM-dd')
      item.riskType = enumRiskType[item.extended_loan_type] || ''

      item.statusLabel = ''
      item.statusColor = ''
      if (item.extended_loan_type === 1) {
        item.statusLabel = enumPostponeStatus[item.approval_status] || ''
        item.statusColor = enumPostponeStatusColor[item.approval_status] || ''
      } else {
        item.statusLabel = enumRenewalStatus[item.approval_status] || ''
        item.statusColor = enumRenewalStatusColor[item.approval_status] || ''
      }
      item.finishDate =
        item.approval_status === 2 ? this.$utils.dateFormat(item.update_time, 'yyyy-MM-dd') : ''

      return item
    },
    handleApproval(row) {
      this.viewMode = 1
      this.editRow = { ...row } || {}
      this.editVisible = true
    },
    handleEdit(row) {
      this.viewMode = 0
      this.editRow = { ...row } || {}
      this.editVisible = true
    },
    handleView(row) {
      this.viewRenewalData = row
      this.viewId = row.customer_related_id
      this.viewVisible = true
    },
    handleFinish(row) {
      this.viewMode = 2
      this.editRow = { ...row } || {}
      this.editVisible = true
    },
    handleDelete(row) {
      this.$utils
        .msgbox({
          message: `确定删除${row.customer_name}?`,
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, this.tableName, row.credit_extended_loan_id),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.handleSuccess()
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
  },
}
</script>

<style lang="scss" scoped></style>
